package com.example.simplejdbcdemo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @description: jdbcTemplate数据库操作类
 * @author: lzp
 * @createTime: 2021-11-20 17:25
 **/
@Repository
@Slf4j
public class FooDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SimpleJdbcInsert simpleJdbcInsert;

    public void insert() {
        Arrays.asList("b", "c").forEach(bar -> {
            jdbcTemplate.update("INSERT INTO FOO (BAR) VALUES (?)", bar);
        });

        HashMap<String, Object> row = new HashMap<>();
        row.put("BAR", "d");
        Number id = simpleJdbcInsert.executeAndReturnKey(row);
        log.info("打印插入数据id：" + id);
    }

    public void list() {
        // 查询某个值
        Long count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO", Long.class);
        log.info("count: {}", count);

        // 查询列表
        List<String> list = jdbcTemplate.queryForList("SELECT BAR FROM FOO", String.class);
        list.forEach(bar -> log.info("BAR: {}", bar));

        // 查询list<map>
        List<Foo> fooList = jdbcTemplate.query("SELECT * FROM FOO",
                // 结果集映射 使用#{RowMapper}
                (rs, rowNum) -> Foo.builder()
                        .id(rs.getLong(1))
                        .bar(rs.getString(2))
                        .build());
        fooList.forEach(foo -> log.info(foo.toString()));
    }
}
